
import { Message } from "@element-plus/icons-vue";
import axios from "axios";


const instance = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    wsBaseURL: import.meta.env.VITE_WS_BASE_URL,
    timeout: 5000,
    withCredentials: false

})

// 请求拦截
instance.interceptors.request.use(
    config => {
        // console.log("所有请求先经过拦截器")
        const token = localStorage.getItem("token")
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        // console.log("拦截器：", config)
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截
instance.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code !== 200) {
            Message.error(res.message || "Error")

            if (res.code === 401) {
                // 处理token失效
                localStorage.removeItem("token")
                window.location.href = "/login"
            }
            return Promise.reject(new Error(res.message || "Error"))
        } else {
            return res
        }
    },
    error => {
        Message.error("网络异常，请检查网络连接")
        return Promise.reject(error)
    }
)

export default instance